<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { getTravelPlans, deleteTravelPlan } from '../../api/travelPlan'
import { authUtils } from '../../utils/auth'

const router = useRouter()
const travelPlans = ref([])
const loading = ref(false)
const searchQuery = ref('')
const currentPage = ref(1)
const pageSize = ref(8)
const totalItems = ref(0)
const filterType = ref('all') // all, public, private

// 模拟数据 - 实际项目中应该从API获取
const mockTravelPlans = [
  {
    id: 1,
    title: '东京五日游',
    description: '探索东京的现代与传统文化',
    mainCity: '东京',
    days: 5,
    startDate: '2023-10-15',
    isPublic: true,
    coverImage: 'https://picsum.photos/800/400?random=1',
    createdAt: '2023-09-01'
  },
  {
    id: 2,
    title: '巴黎浪漫之旅',
    description: '体验巴黎的艺术与浪漫',
    mainCity: '巴黎',
    days: 7,
    startDate: '2023-11-20',
    isPublic: true,
    coverImage: 'https://picsum.photos/800/400?random=2',
    createdAt: '2023-09-10'
  },
  {
    id: 3,
    title: '北京文化探索',
    description: '领略中国首都的历史与现代魅力',
    mainCity: '北京',
    days: 4,
    startDate: '2023-12-05',
    isPublic: false,
    coverImage: 'https://picsum.photos/800/400?random=3',
    createdAt: '2023-09-15'
  },
  {
    id: 4,
    title: '纽约城市体验',
    description: '探索纽约的繁华与多元文化',
    mainCity: '纽约',
    days: 6,
    startDate: '2024-01-10',
    isPublic: true,
    coverImage: 'https://picsum.photos/800/400?random=4',
    createdAt: '2023-09-20'
  },
  {
    id: 5,
    title: '香港美食之旅',
    description: '品尝香港的各式美食与文化',
    mainCity: '香港',
    days: 3,
    startDate: '2023-10-25',
    isPublic: true,
    coverImage: 'https://picsum.photos/800/400?random=5',
    createdAt: '2023-09-25'
  },
  {
    id: 6,
    title: '上海都市游',
    description: '体验上海的现代都市魅力',
    mainCity: '上海',
    days: 4,
    startDate: '2023-11-05',
    isPublic: false,
    coverImage: 'https://picsum.photos/800/400?random=6',
    createdAt: '2023-10-01'
  },
  {
    id: 7,
    title: '伦敦文化之旅',
    description: '探索伦敦的历史与文化',
    mainCity: '伦敦',
    days: 6,
    startDate: '2023-12-15',
    isPublic: true,
    coverImage: 'https://picsum.photos/800/400?random=7',
    createdAt: '2023-10-10'
  },
  {
    id: 8,
    title: '悉尼海滩假期',
    description: '享受悉尼的阳光与海滩',
    mainCity: '悉尼',
    days: 7,
    startDate: '2024-01-20',
    isPublic: true,
    coverImage: 'https://picsum.photos/800/400?random=8',
    createdAt: '2023-10-15'
  },
  {
    id: 9,
    title: '罗马历史探索',
    description: '领略罗马的古代文明',
    mainCity: '罗马',
    days: 5,
    startDate: '2023-11-25',
    isPublic: false,
    coverImage: 'https://picsum.photos/800/400?random=9',
    createdAt: '2023-10-20'
  }
]

// 筛选和搜索旅行计划
const filteredPlans = computed(() => {
  let result = [...travelPlans.value]

  // 根据类型筛选
  if (filterType.value !== 'all') {
    const isPublic = filterType.value === 'public'
    result = result.filter((plan) => !!plan.isPublic === isPublic)
  }

  // 根据搜索词筛选
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    result = result.filter(
      (plan) =>
        (plan.title || '').toLowerCase().includes(query) ||
        (plan.description || '').toLowerCase().includes(query) ||
        (plan.mainCity || plan.cityName || '').toLowerCase().includes(query)
    )
  }

  totalItems.value = result.length

  // 分页
  const startIndex = (currentPage.value - 1) * pageSize.value
  const endIndex = startIndex + pageSize.value
  return result.slice(startIndex, endIndex)
})

// 获取旅行计划列表（使用后端接口，按当前用户过滤）
const fetchTravelPlans = async () => {
  loading.value = true
  try {
    const currentUser = authUtils.getCurrentUser()
    const currentUserId = currentUser?.id
    const data = await getTravelPlans(currentUserId ? { userId: currentUserId } : {});
    // 统一字段映射
    const allPlans = (data || []).map(p => ({
      ...p,
      mainCity: p.cityName || '',
      createdAt: p.created_at
    }));
    // 后端已按用户过滤，这里直接赋值
    travelPlans.value = allPlans
    totalItems.value = travelPlans.value.length;
  } catch (error) {
    console.error('获取旅行计划列表失败:', error)
    ElMessage.error('获取旅行计划列表失败')
  } finally {
    loading.value = false
  }
}

// 创建新计划
const createNewPlan = () => {
  router.push('/travel-plan/new')
}

// 查看计划详情
const viewPlanDetail = (id) => {
  router.push(`/travel-plan/${id}`)
}

// 编辑计划
const editPlan = (id) => {
  router.push(`/travel-plan/${id}/edit`)
}

// 删除计划（调用后端接口）
const deletePlan = async (id) => {
  try {
    const ok = await deleteTravelPlan(id)
    if (ok) {
      ElMessage.success('删除成功')
      await fetchTravelPlans()
    }
  } catch (error) {
    console.error('删除计划失败:', error)
    ElMessage.error('删除计划失败')
  }
}

// 处理页码变化
const handlePageChange = (page) => {
  currentPage.value = page
}

// 处理筛选变化
const handleFilterChange = (type) => {
  filterType.value = type
  currentPage.value = 1 // 重置到第一页
}

// 重置搜索
const resetSearch = () => {
  searchQuery.value = ''
  filterType.value = 'all'
  currentPage.value = 1
}

onMounted(() => {
  fetchTravelPlans()
})
</script>

<template>
  <div class="travel-plan-list-container">
    <div class="page-header">
      <h1>旅游计划</h1>
      <el-button type="primary" @click="createNewPlan">创建新计划</el-button>
    </div>

    <!-- 搜索和筛选区域 -->
    <div class="search-filter-container">
      <div class="search-box">
        <el-input
          v-model="searchQuery"
          placeholder="搜索旅行计划..."
          clearable
          @clear="resetSearch"
        >
          <template #prefix>
            <i class="el-icon-search"></i>
          </template>
        </el-input>
      </div>

      <div class="filter-buttons">
        <el-radio-group v-model="filterType" @change="handleFilterChange">
          <el-radio-button label="all">全部</el-radio-button>
          <el-radio-button label="public">公开</el-radio-button>
          <el-radio-button label="private">私密</el-radio-button>
        </el-radio-group>
      </div>
    </div>

    <el-skeleton :rows="5" animated v-if="loading" />

    <div v-else-if="filteredPlans.length === 0" class="empty-state">
      <el-empty description="暂无符合条件的旅行计划" />
      <div class="empty-actions">
        <el-button @click="resetSearch">重置筛选</el-button>
        <el-button type="primary" @click="createNewPlan">创建新计划</el-button>
      </div>
    </div>

    <div v-else class="travel-plan-list">
      <el-card
        v-for="plan in filteredPlans"
        :key="plan.id"
        class="travel-plan-card"
        shadow="hover"
      >
        <div class="card-content">
          <div class="card-image">
            <img :src="plan.coverImage" :alt="plan.title" />
            <div class="plan-days">{{ plan.days }}天</div>
          </div>
          <div class="card-info">
            <h3 class="plan-title" @click="viewPlanDetail(plan.id)">
              {{ plan.title }}
            </h3>
            <p class="plan-description">{{ plan.description }}</p>
            <div class="plan-meta">
              <span><i class="el-icon-location"></i> {{ plan.mainCity }}</span>
              <span><i class="el-icon-date"></i> {{ plan.startDate }}</span>
              <el-tag size="small" :type="plan.isPublic ? 'success' : 'info'">
                {{ plan.isPublic ? '公开' : '私密' }}
              </el-tag>
            </div>
          </div>
          <div class="card-actions">
            <el-button type="text" @click="viewPlanDetail(plan.id)"
              >查看</el-button
            >
            <el-button type="text" @click="editPlan(plan.id)">编辑</el-button>
            <el-popconfirm
              title="确定删除该旅行计划吗？"
              @confirm="deletePlan(plan.id)"
            >
              <template #reference>
                <el-button type="text">删除</el-button>
              </template>
            </el-popconfirm>
          </div>
        </div>
      </el-card>
    </div>

    <!-- 分页 -->
    <div class="pagination-container" v-if="totalItems > 0">
      <el-pagination
        background
        layout="prev, pager, next"
        :total="totalItems"
        :page-size="pageSize"
        :current-page="currentPage"
        @current-change="handlePageChange"
      />
    </div>
  </div>
</template>

<style scoped>
.travel-plan-list-container {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  font-size: 28px;
  margin: 0;
}

.search-filter-container {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  flex-wrap: wrap;
  gap: 15px;
}

.search-box {
  flex: 1;
  min-width: 250px;
}

.filter-buttons {
  display: flex;
  align-items: center;
}

.empty-state {
  text-align: center;
  padding: 40px 0;
}

.empty-actions {
  margin-top: 20px;
  display: flex;
  justify-content: center;
  gap: 10px;
}

.travel-plan-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(350px, 1fr));
  gap: 20px;
  margin-bottom: 30px;
}

.travel-plan-card {
  color: #0a192f;
  transition: transform 0.3s;
}

.travel-plan-card:hover {
  transform: translateY(-5px);
}

.card-content {
  display: flex;
  flex-direction: column;
}

.card-image {
  position: relative;
  height: 180px;
  overflow: hidden;
}

.card-image img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.plan-days {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 5px 10px;
  border-radius: 4px;
  font-weight: bold;
}

.card-info {
  padding: 15px 0;
}

.plan-title {
  margin: 0 0 10px;
  cursor: pointer;
  color: #303133;
}

.plan-title:hover {
  color: #409eff;
}

.plan-description {
  color: #606266;
  margin: 0 0 15px;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.plan-meta {
  display: flex;
  align-items: center;
  gap: 15px;
  color: #909399;
  font-size: 14px;
}

.card-actions {
  display: flex;
  justify-content: flex-end;
  border-top: 1px solid #ebeef5;
  padding-top: 10px;
  margin-top: 10px;
}

.pagination-container {
  display: flex;
  justify-content: center;
  margin-top: 30px;
}
</style>
